package com.qitmiaojie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qitmiaojie.controller.utils.Result;
import com.qitmiaojie.pojo.Notice;
import com.qitmiaojie.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
//公告通知
public class NoticeController {
    @Autowired
    private NoticeService noticeService;
    /**
     * 删除公告 需要有删除公告权限
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('advice:manage:release:delete')")
    @DeleteMapping("/notice/{id}")
    public Result del(@PathVariable Integer id){
        noticeService.removeById(id);
        return Result.success("删除成功",null);
    }

    /**
     * 发布公告
     * @param notice
     * @return
     */
    @PostMapping("/notice")
    public Result addNotice(@RequestBody Notice notice){
        log.info(notice.toString());
        noticeService.saveOrUpdate(notice);
        return Result.success("ok!",null);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/notice")
    public Result list(){
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Notice::getDatetime);
        List<Notice> list = noticeService.list(queryWrapper);

        return Result.success(list);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/notice/{id}")
    public Result one(@PathVariable Integer id){
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getId,id);
        Notice one = noticeService.getOne(queryWrapper);

        return Result.success(one);
    }

    /**
     *
     * @return
     */
    @GetMapping("/notice/new")
    public Result newNotice(){
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Notice::getDatetime);
        Page<Notice> pages = new Page<>(1,1);
        noticeService.page(pages,queryWrapper);
        List<Notice> records = pages.getRecords();
        log.info(records.toString());
        return Result.success(records);
    }
}
